package com.woniu.order.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.exception.userexp.YogaException;
import com.woniu.model.Result;
import com.woniu.order.Form.OrderByShoppingCarForm;
import com.woniu.order.Form.PageForm;
import com.woniu.order.Param.OrderByShoppingCarParam;
import com.woniu.order.Param.OrderPayParam;
import com.woniu.order.Param.PageParam;
import com.woniu.order.dto.GoodsOrderDto;
import com.woniu.order.model.GoodsOrder;
import com.woniu.order.service.GoodsOrderService;
import com.woniu.util.JwtUtil;
import com.woniu.util.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 杜岷芫
 * @since 2024年07月12日
 */
@RestController
@RequestMapping("/goodsOrder")
@Api(tags = "商城订单的接口")
public class GoodsOrderController {
    @Resource
    private GoodsOrderService goodsOrderService;
    @Resource
    private RedisUtil redisUtil;

    @PostMapping("/selectOrders")
    @ApiOperation(value = "用户查询自己订单")
    private Result selectOrders(@RequestBody PageForm form, @RequestHeader String token) throws Exception {
        String refreshToken = redisUtil.get(token);//从短token取出键
        int userId = Integer.parseInt(JwtUtil.parseUserToken(refreshToken).get("userId").toString());

        Page<GoodsOrder> page = goodsOrderService.selsectOrders(BeanUtil.toBean(form, PageParam.class), userId);

        return Result.getResult(Page.class).setData(page).setCode(200).setMsg("查询成功");
    }
    //发起支付
    @GetMapping("/pay")
    @ApiOperation(value = "发起支付")
    public Result pay(String orderNum, @RequestHeader String token) throws Exception {
        String refreshToken = redisUtil.get(token);//从短token取出键
        int userId = Integer.parseInt(JwtUtil.parseUserToken(refreshToken).get("userId").toString());

        OrderPayParam orderPayParam = new OrderPayParam();
        orderPayParam.setOrderNum(orderNum);
        orderPayParam.setUserId(userId);

        return Result.getResult(null).setCode(200).setMsg("发起支付成功").setData(goodsOrderService.pay(orderPayParam));
    }
    @PostMapping("/notify")
    @ApiOperation(value = "给支付宝回调的接口")
    public String payNotify(HttpServletRequest request) throws Exception {
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        goodsOrderService.payNotify(params);
        return "SUCCESS";
    }

    //商城下单订单接口
    @PostMapping("orderByShoppingCar")
    @ApiOperation("商城订单下单接口")
    public Result order(@RequestBody OrderByShoppingCarForm form, @RequestHeader String token) throws Exception {

        String refreshToken = redisUtil.get(token);//从短token取出键
        int userId = Integer.parseInt(JwtUtil.parseUserToken(refreshToken).get("userId").toString());

        OrderByShoppingCarParam param = BeanUtil.toBean(form, OrderByShoppingCarParam.class);
        param.setUserId(userId);

        GoodsOrderDto dto = goodsOrderService.orderByShoppingCar(param);
        return Result.getResult().setCode(200).setMsg("下单成功").setData(dto);
    }
    //通过一个订单编号查询一个订单回去
    @GetMapping("/byId/{id}")
    @ApiOperation(value = "通过一个订单编号查询一个订单回去")
    public Result<GoodsOrder>byId(@PathVariable("id") String orderNum){
        GoodsOrder goodsOrder = goodsOrderService.getById(orderNum);

        return Result.getResult(GoodsOrder.class).setData(goodsOrder).setCode(200).setMsg("查询成功");
    }


     // getOneId通过一个订单编号查询一个订单回去
    @GetMapping("/getOneId/{id}")
    @ApiOperation(value = "getOneId通过一个订单编号查询一个订单回去")
    public Result<GoodsOrder>getOneId(@PathVariable("id") String orderNum){
        GoodsOrder goodsOrder = goodsOrderService.getOneId(orderNum);
        return Result.getResult(GoodsOrder.class).setData(goodsOrder).setCode(200).setMsg("查询成功");
    }
    //传订单对象，根据id修改信息
    @PostMapping("/updateByIdGoodsOrder")
    @ApiOperation(value = "传一个订单对象，根据id去修改里面的信息")
    public Result updateByIdGoodsOrder(@RequestBody GoodsOrder GoodsOrder)throws YogaException{
        goodsOrderService.updateByIdGoodsOrder(GoodsOrder);
        return Result.getResult().setCode(200).setMsg("修改成功");
    }
    //分页查询
    @GetMapping("/loadPageGoodsOrder")
    @ApiOperation(value = "分页查询订单接口")
    public Result loadPageGoodsOrder( PageForm form) throws YogaException {
        Page<GoodsOrder> page = goodsOrderService.loadPageGoodsOrder(BeanUtil.toBean(form, PageParam.class));
        return Result.getResult().setMsg("查询成功").setCode(200).setData(page);
    }
}

